﻿var hier_id;
var vers_id;
var table_name;
var node_id;
var selected_node;
var node_vals;
var nodeData = { data: null };
var tempNodeId = new Array();
var dimtable_name;
var bmoveRelflag=false;
//var root_flag = false;

function BindOptional() {
    //debugger;
    $("#demo")
    .bind("before.jstree", function (e, data) {
        if (data.func === "open_node") {
            ////////////debugger;
            data.args[0].attr("root_flag", false);
        }
    })
    .jstree({
        //"core" : { "initially_open" : [ "root" ] },
        "html_data": {
            "data": "<li id='root'><a href='#'>Root node</a><ul><li><a href='#'>Child node</a></li></ul></li>"
        },
        "plugins": ["themes", "html_data"]
    });
}

function BindTree(root_flag) {
   //debugger;

    $("#demo")
	.jstree({
	    // List of active plugins
	    "plugins": [
	        "themes", "json_data", "ui", "crrm", "dnd", "search", "types", "hotkeys", "contextmenu"
		],

	    // I usually configure the plugin that handles the data first
	    // This example uses JSON as it is most common
	    "json_data": {
	        // This tree is ajax enabled - as this is most common, and maybe a bit more complex
	        // All the options are almost the same as jQuery's AJAX (read the docs)
	        "ajax": {
	            // the URL to fetch the data
	            "url": "Callback.aspx", //+ urlParams,
	            // the `data` function is executed in the instance's scope
	            // the parameter is the node being loaded 
	            // (may be -1, 0, or undefined when loading the root nodes)
	            "data": function (n) {
	                ////////debugger;
	                // the result is fed to the AJAX request `data` option
	                return {
	                    "operation": "get_children",
	                    //"operation" : "get_root", 
	                    "id": n.attr ? n.attr("id").replace("node_", "") : "",
	                    //"table_name": table_name, changed by poonam on 7 october 2011
	                    "table_name": $("#drp_hier option:selected").data("TableName"),
	                    "hier_id": hier_id,
	                    "vers_id": vers_id,
	                    "root_flag": root_flag,
	                    "txtdate": $('#txt_date').val()
	                };
	            }
	        }
	    },

	    "contextmenu": { "items": customMenu },


	    // Configuring the search plugin
	    "search": {
	        // As this has been a common question - async search
	        // Same as above - the `ajax` config option is actually jQuery's AJAX object
	        "ajax": {
	            "url": "Callback.aspx",
	            // You get the search string as a parameter
	            "data": function (str) {
	                return {
	                    "operation": "search",
	                    "search_str": str
	                };
	            }
	        }
	    },

	    // Using types - most of the time this is an overkill
	    // read the docs carefully to decide whether you need types
	    "types": {
	        // I set both options to -2, as I do not need depth and children count checking
	        // Those two checks may slow jstree a lot, so use only when needed
	        "max_depth": -2,
	        "max_children": -2,
	        // I want only `drive` nodes to be root nodes 
	        // This will prevent moving or creating any other type as a root node
	        "valid_children": ["folder"],
	        "types": {
	            // The default type
	            "default": {
	                // I want this type to have no children (so only leaf nodes)
	                // In my case - those are files
	                "valid_children": "none",
	                // If we specify an icon for the default type it WILL OVERRIDE the theme icons
	                "icon": {
	                    "image": "../Images/file.png"
	                }
	            },
	            // The `folder` type
	            "folder": {
	                // can have files and other folders inside of it, but NOT `drive` nodes
	                "valid_children": ["default", "folder"],
	                "icon": {
	                    "image": "../Images/folder.png"
	                }
	            }
	        }
	    },
	    // UI & core - the nodes to initially select and open will be overwritten by the cookie plugin


	    // the UI plugin - it handles selecting/deselecting/hovering nodes
	    "ui": {
	    // this makes the node with ID node_4 selected onload
	    //"initially_select" : [ "node_4" ]
	},
	// the core plugin - not many options here
	"core": {
	// just open those two nodes up
	// as this is an AJAX enabled tree, both will be downloaded from the server
	// "initially_open" : [ "node_2" , "node_3" ] 
},

"crrm": {
    "move": {
        "check_move": function (data) {
            //debugger;
            var optval = $("input[name='sdate']:checked").val();
            return (optval === "histdate") ? false : true;

            //           if (optval == "histdate") {
            //               //e.stopImmediatePropagation();
            //                return false;

            //            }
            //            else {

            //                var typeid = data.o.attr('typeid'); //data.r.attr('typeid')	 data.o.attr('validparent')
            //                var desttypeid = data.r.attr('typeid');
            //                var validpPar = data.o.attr('validparent').split(',');
            //                //desttypeid
            //                // var pos = jQuery.inArray("John", validpPar);
            //                var pos = jQuery.inArray(desttypeid, validpPar);
            //                if (pos == -1) {
            //                    //e.stopImmediatePropagation();
            //                    return false;                    
            //                }
            //                else {
            //                    return true;
            //                }
            //            }

            //alert(desttypeid);
            //alert(desttypeid === "1");
            //return (desttypeid === "1") ? false : true;
            // var arr = data.o.attr('validparent');
            // var flag = arr.filter(function () { return this.value === ''; });

        }
    }

}

})


    // My Defined Functions starts
    .bind("before.jstree", function (e, data) {
        var nodename;
        if (data.func === "open_node") {
            //////debugger;
            root_flag = false;
            //defaults = $.jstree._focused().defaults;
        }
        if (data.func === "show_contextmenu") {
            //////debugger;
            root_flag = false;
        }

        if (data.plugin === "types") {
            //////debugger;
            //root_flag = false;
        }

        //remove confirmation
        if (data.func === "remove") {
            nodename = $.trim(data.args[0].children("a").text());
            //var isleaf = $.trim(data.args[0].attr('isleaf'));
            var hasdata = $.trim(data.args[0].attr('hasdata'));

            if (hasdata == "1") {
                alert("Cannot delete ! all child nodes either should be inactivated or moved to different node !");
                e.stopImmediatePropagation();
                return false;
            }
            else {
                if (data.func === "remove" && !confirm("Are you sure you want to delete " + nodename + " ?")) {
                    e.stopImmediatePropagation();
                    return false;
                }
            }
        }

        // move confirmation
        if (data.func == "move_node" && data.args[1] == false && data.plugin == "core" && data.args[0].o != undefined) {
            ////debugger;
            var optval = $("input[name='sdate']:checked").val();
            if (optval != 'todate') {
                e.stopImmediatePropagation();
                return false;
            }

            //alert($(".jstree-invalid").length); 
            if ($(".jstree-invalid").length == 0) { //check with naval
                ////debugger;
                nodename = $.trim(data.args[0].o.children("a").text());
                var destparent = $.trim(data.args[0].np.children("a").text());
                var orgparent = $.trim(data.args[0].op.children("a").text());
                var msg;
                if (destparent == orgparent) {
                    msg = "Are you sure you want to change order ?";
                }
                else {
                    msg = "Are you sure you want to move '" + nodename + "' to '" + destparent + "' ?";
                }

                //if (confirm("Are you sure you want to move '" + nodename + "' to '" + destparent + "' ?") === false) {
                if (confirm(msg) === false) {
                    e.stopImmediatePropagation();
                    return false;
                }

                ////debugger;
                var msgRel = false;
                msgRel = "Do you want to move the related data ?";
                if (confirm(msgRel) === true) {
                    bmoveRelflag = true;
                }
            }
        }
    })

    //    .bind("loaded.jstree", function (e, data) {
    //         debugger;
    //         var $nodes = data.rslt.obj;
    //     })

    //    .bind("reopen.jstree", function (e, data) {
    //         debugger;
    //         var $nodes = data.rslt.obj;
    //     })


    //    .bind('load_node.jstree', function (e, data) {
    //         debugger;
    //         var $nodes = data.rslt.obj;

    //         if ($nodes == -1) {
    //             // Loaded the root node, however jstree doesn't tell us
    //             // what the nodes are. We have to find them ourselves.
    //             $nodes = $('#tree').find('ul:first-child > li');

    //             // data.inst._get_children(data.rslt.obj)
    //             //This way you will always get the new nodes that were inserted.
    //         }
    //         //....
    //     })

    //remove tree fuction
	.bind("remove.jstree", function (e, data) {
	    data.rslt.obj.each(function () {
	        $.ajax({
	            async: true,
	            type: 'POST',
	            url: "Callback.aspx?operation=remove_node&id=" + $(data.rslt.obj).attr("id") + "&table_name=" + table_name + "&txtdate=" + $('#txt_date').val(),
	            success: function (r) {
	                if (r == "false") {
	                    $.jstree.rollback(data.rlbk);
	                    alert("Cannot delete ! all child nodes either should be inactivated or moved to different node !");
	                    return false;
	                }
	                else if (r == "true") {
	                    alert("removed sucessfully !");
	                }
	            }
	        });
	    });
	})


    //funstion for select node 
	.bind("select_node.jstree", function (e, data) {

	    //debugger;
	    // index of tab
	    var $tabs = $("#tabsDim").tabs();
	    var selected_ind = $tabs.tabs('option', 'selected'); // => index of tab
	    var tabname = $('#tabsDim a')[selected_ind].hash;

	    if (selected_ind == 0) {
	        //show attributes
	        //getAttr(e, data);
	        getAttr();
	    }
	    else {
	        //show dimensions
	        //var dimtabName = ui.panel.id;
	        ////debugger;
	        var dimtabName = $('#tabsDim a')[selected_ind].hash;
	        dimtabName = dimtabName.replace('#', '');

	        node_id = $(data.rslt.obj).attr("id");

	        if (node_id == undefined) { node_id = 0; }
	        //ui.panel.id
	        debugger;

	        if ($(data.rslt.obj).attr("isleaf") == "1") {
	            $('input[id=btn' + dimtabName + '_arel]').show();
	            $('input[id=btn' + dimtabName + '_rrel]').show();
	        }
	        else {
	            $('input[id=btn' + dimtabName + '_arel]').hide();
	            $('input[id=btn' + dimtabName + '_rrel]').hide();
	        }

	        //disable "rule tab"
	        //depending on if it is root node
	        if ($(data.rslt.obj).attr("id") == "1" || $(data.rslt.obj).attr("validparent") == "") {
	            $("#" + dimtabName).tabs('select', 0);
	            $("#" + dimtabName).tabs({ disabled: [1] });
	        }
	        else {
	            $("#" + dimtabName).tabs('enable', 1);
	        }

	        if (tempNodeId[selected_ind] != node_id) {
	            //$("#tab" + thistab).html(getGridData(dimtabName));
	            loadGriddataDim(dimtabName, node_id, selected_ind, "exist", "false");
	        }

	    }
	})

	.bind("open_node.jstree", function (e, data) {
	    ////debugger;
	    var insIcon = $("jstree-focused a ins.jstree-icon");
	    var liIcon = $("jstree-focused li");

	    //append class "jstree-leaf" if it is leaf node
	    //filter on attribute hasdata=0
	    //$("li", data.args[0]).addClass("jstree-leaf");
	    $('[hasdata=0]', data.args[0]).filter("li").addClass("jstree-leaf");
	    // $('[hasdata=0]', data.args[0]).addClass("jstree-leaf");
	})

    //function for rename 
	.bind("rename.jstree", function (e, data) {
	    ////////debugger;
	    node_id = $(data.rslt.obj).attr("id");
	    $.ajax({
	        async: true,
	        type: 'POST',
	        url: "Callback.aspx?operation=rename_node&id=" + $(data.rslt.obj).attr("id") + "&table_name=" + table_name + "&new_name=" + data.rslt.new_name,
	        success: function (str) {
	            //$.jstree.rollback(data.rlbk);
	        }
	    });
	})

    //function for move node
	.bind("move_node.jstree", function (e, data) {
	    // //debugger;
	    //var selected_ind = $tabs.tabs('option', 'selected'); // => index of tab
	    //var dimtabName = $('#tabsDim a')[selected_ind].hash;
	    // alert(dimtabName);

	    data.rslt.o.each(function (i) {
	        $.ajax({
	            async: true,
	            type: 'POST',
	            url: "Callback.aspx?operation=move_node&id=" + $(this).attr("id") + "&table_name=" + table_name + "&vers_id=" + vers_id + "&hier_id=" + hier_id + "&copy=" + data.rslt.cy + "&refid=" + data.rslt.np.attr("id") + "&txtdate=" + $('#txt_date').val() + "&type_id=" + $(this).attr("typeid") + "&bmoveRelflag=" + bmoveRelflag,
	            success: function (r) {
	                //debugger;

	                if (r == "false") {
	                    $.jstree.rollback(data.rlbk);
	                    alert("Can't move to this parent !");
	                    return false;
	                }
	                else {

	                    var totid = r.split(";");
	                    var movedid = 0;
	                    var i;
	                    for (i = 0; i < totid.length - 1; i++) {
	                        var newoldid = totid[i].split(",");
	                        $("#" + newoldid[0]).attr('id', newoldid[1]);

	                        if (i == 0) { movedid = newoldid[1]; }

	                    }

	                    //alert("moved successfully !");
	                    //refresh all exist grid
	                    if (bmoveRelflag == false) {

	                        var dimname;

	                        //node_id = $(data.rslt.obj).attr("id");
	                        node_id = movedid;

	                        if (node_id == undefined) { node_id = 0; }

	                        for (i = $('#tabsDim').tabs('length') - 1; i > 0; i--) {

	                            dimname = $('#tabsDim a')[i].hash;
	                            dimname = dimname.replace('#', '');

	                            var tblnameEx = "#dtgrid" + dimname + "ex";
	                            var pgnameEx = "#pg" + dimname + "ex";
	                            var opr = "get_griddata";
	                            var url = "Callback.aspx?operation=" + opr + "&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&txtdate=" + $('#txt_date').val();

	                            refreshgrid("griddata.gridEx", tblnameEx, url);
	                        }
	                        ///
	                    }
	                }
	            }

	        });
	    });
	});
}

//to ger attribute data
//function getAttr(e, data) {
function getAttr() {

    var optval = $("input[name='sdate']:checked").val();

   // node_id = $(data.rslt.obj).attr("id");
    var node_id = $("#demo").jstree('get_selected').attr("id");
    //debugger;

    if (tempNodeId[0] != node_id) {

        tempNodeId[0] = node_id;

        var typeid = $('#demo').jstree('get_selected').attr('typeid');
        var hier_id = $("#drp_hier").val();

        $.ajax({
            async: true,
            type: 'POST',
            //url: "Callback.aspx?operation=select_item&id=" + $(data.rslt.obj).attr("id") + "&table_name=" + table_name + "&type_id=" + typeid + "&hier_id=" + hier_id + "&txtdate=" + $('#txt_date').val(),
            url: "Callback.aspx?operation=select_item&id=" + node_id + "&table_name=" + table_name + "&type_id=" + typeid + "&hier_id=" + hier_id + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val(),
            success: function (str) {

                //debugger;
                var data = eval('(' + str + ')');
                $("#NodeAttr").empty();
                $("#tmplAttr").tmpl(data).appendTo("#NodeAttr");

                // $("#NodeAttr").css("display", "block");
                $("#NodeAttr").show();

                if (optval == 'todate') {
                    //$("#tbl_Buttons").css("display", "block");
                    $("#tbl_Buttons").show();
                }
                else {
                   // $("#tbl_Buttons").css("display", "none");
                    $("#tbl_Buttons").hide();
                }

                //add calender control to date type attributes
                $("input[control_type='calender']").datepicker();

                $("input[datatype='NUMBER']").blur(function () {
                    numberOnly(this);
                });

                $("input[control_type='calender']").blur(function () {
                    isValidDate(this);
                });

                $("#btn_Cancel").click(function () {
                    ClearAttributes();
                });

            }
        });
    }
}


//custom menu
function customMenu(node) {

    //debugger;

    var optval = $("input[name='sdate']:checked").val();
    var items;

    if (optval == "todate") {
        var isleaf = node.attr("isleaf");
        var bflag = true;
        if (isleaf == "0") { bflag = false; } else { bflag = true; }

        // The default set of all items
        items = { // Could be a function that should return an object like this one
            "create": {
                "separator_before": false,
                "separator_after": true,
                "label": "Add Child Node", // Change Naval 
                "_disabled": bflag,     // clicking the item won't do a thing 
                "action": function (obj) { showCreateOptions(obj); }
            },
            "rename": {
                "separator_before": false,
                "separator_after": true,
                "label": "Rename",
                "action": function (obj) { this.rename(obj); }
            },
            "remove": {
                "separator_before": false,
                "icon": false,
                "separator_after": true,
                "label": "Delete",
                "action": function (obj) { if (this.is_selected(obj)) { this.remove(); } else { this.remove(obj); } }
            }  
            
            //changed by poonam to disable cut and paste
            //,
            //newly added menu in context menu by poonam on 09082011
//            "cut": {
//                "separator_before": false,
//                "separator_after": false,
//                "label": "Cut",
//                "action": function (obj) { this.cut(obj); }
//            },
//            "paste": {
//                "separator_before": false,
//                "icon": false,
//                "separator_after": false,
//                "label": "Paste",
//                "action": function (obj) { this.paste(obj); }
//            }
            //comment done by poonam on 09082011 for remove edit menu 
            //and bring ccp in menu directly
        }
    }

    else {
        //don't make menu if radio button historical is selectes
        items = { create: false,
            rename: false,
            remove: false,
            ccp: false
        };
    }

    return items;
}

//on click of add child node add dialog option
function showCreateOptions(obj) {
    ////debugger;
    //selected_node = this._get_node(obj, true);
    selected_node = $.jstree._focused()._get_node(obj);
    var id = $(selected_node).attr("id");
    var type_id = $(selected_node).attr("typeid");
    var table_name = $("#drp_hier option:selected").data("TableName");
    var hier_id = $("#drp_hier").val();

    var DialogOptions = "Center=Yes; Scrollbar=No; dialogWidth=400px; dialogTop=250px; dialogHeight=250px; Help=No; Status=No; Resizable=No;";
    var OpenUrl = "CreateMenuOptions.aspx?id=" + id + "&type_id=" + type_id + "&hier_id=" + hier_id + "&vers_id=" + $("#drp_ver").val() + "&table_name=" + table_name + "&txtdate=" + $('#txt_date').val();
    var ret = window.showModalDialog(OpenUrl, "Yes", DialogOptions);

    if (typeof (ret) != "undefined") {
        //////debugger;
        node_vals = eval('(' + ret + ')');
        var new_type_id = $("#" + node_vals.NodeType).attr("typeid");
        createnode(obj);
    }
}

//after closing create-dialog creates node in UI and add in database
function createnode(obj) {

    selected_node = $.jstree._focused()._get_node(obj);
    var id = $(selected_node).attr("id");
    var table_name = $("#drp_hier option:selected").data("TableName");
    var retval;

    ////debugger;

    $.ajax({
        async: true,
        type: 'POST',
        //        url: "Callback.aspx?operation=create_node&id=" + id + "&type_id=" + node_vals.NodeType + "&hier_id=" + $("#drp_hier").val()  +
        //        url: "Callback.aspx?operation=create_node&id=" + id + "&type_id=" + $(selected_node).attr("typeid") + "&hier_id=" + $("#drp_hier").val() +
        //"&table_name=" + table_name + "&vers_id=" + $("#drp_ver").val() + "&new_name=" + node_vals.NodeName + "&newnode_id=" + node_vals.NodeType,

        url: "Callback.aspx?operation=create_node&id=" + id + "&type_id=" + $(selected_node).attr("typeid") + "&hier_id=" + $("#drp_hier").val() +
             "&table_name=" + table_name + "&vers_id=" + $("#drp_ver").val() + "&new_name=" + node_vals.NodeName + "&newnode_typeid=" + node_vals.NodeType,

        success: function (str) {
            //alert(str);
            // //debugger;
            var arr = str.split(':');
            var is_leaf = "0";
            if (arr[1] == "1")
            { is_leaf = "0"; } else { is_leaf = "1" };

            var objnode = { attr: { id: arr[0], rel: node_vals.rel, typeid: node_vals.NodeType, isleaf: is_leaf }, data: node_vals.NodeName };
            var tree = jQuery.jstree._focused();
            ////debugger;
            //temp solution for double creation of node //ask to naval 22-11-2011
            $("#demo").jstree("open_node", $("#" + id));
            tree.create(selected_node, 'inside', objnode, function () { }, true);
            return str;
        }
    });
}


function customTypes() {
    ////debugger;
    var types = {
        // The default type
        "default": {
            // I want this type to have no children (so only leaf nodes)
            // In my case - those are files
            "valid_children": "none",
            // If we specify an icon for the default type it WILL OVERRIDE the theme icons
            "icon": {
                "image": "../Images/file.png"
            }
        },
        // The `folder` type
        "folder": {
            // can have files and other folders inside of it, but NOT `drive` nodes
            "valid_children": ["default", "folder"],
            "icon": {
                "image": "../Images/folder.png"
            }
        },
        // The `drive` nodes 
        "drive": {
            // can have files and folders inside, but NOT other `drive` nodes
            "valid_children": ["default", "folder"],
            "icon": {
                "image": "../Images/root.png"
            },
            // those prevent the functions with the same name to be used on `drive` nodes
            // internally the `before` event is used
            "start_drag": false,
            "move_node": false,
            "delete_node": false,
            "remove": false
        }
    }
    return types;
}


function ChangeTypes() {
    ////debugger;
    settings = $('#demo').jstree('get_settings');
    //settings.contextmenu = { 'items': menu };
    settings.types = { 'types': function () {
        // The default type
        var objTypes = {
            "default": {
                // I want this type to have no children (so only leaf nodes)
                // In my case - those are files
                "valid_children": "none",
                // If we specify an icon for the default type it WILL OVERRIDE the theme icons
                "icon": {
                    "image": "../Images/file.png"
                }
            },
            // The `folder` type
            "folder": {
                // can have files and other folders inside of it, but NOT `drive` nodes
                "valid_children": ["default", "folder"],
                "icon": {
                    "image": "../Images/folder.png"
                }
            },
            // The `drive` nodes 
            "drive": {
                // can have files and folders inside, but NOT other `drive` nodes
                "valid_children": ["default", "folder"],
                "icon": {
                    "image": "../Images/root.png"
                },
                // those prevent the functions with the same name to be used on `drive` nodes
                // internally the `before` event is used
                "start_drag": false,
                "move_node": false,
                "delete_node": false,
                "remove": false
            }
        }
        return objTypes;
    }
    }
    $('#demo').jstree('set_settings', settings);
    $('#demo').jstree('refresh', -1);

    //$('#tree').jstree('show_contextmenu', '#' + id);
    //$.jstree._focused().trigger('types');

}

